package com.smartaccounting.service;

import com.smartaccounting.dao.UserDAO;
import com.smartaccounting.model.User;
import com.smartaccounting.util.PasswordUtil;

import java.sql.SQLException;
import java.util.List;

public class UserService {
    private UserDAO userDAO;

    public UserService() {
        this.userDAO = new UserDAO();
    }

    public User authenticate(String username, String password) throws SQLException {
        User user = userDAO.getUserByUsername(username);
        if (user != null && PasswordUtil.checkPassword(password, user.getPassword())) {
            return user;
        }
        return null;
    }

    public boolean registerUser(User user) throws SQLException {
        // 加密密码
        user.setPassword(PasswordUtil.hashPassword(user.getPassword()));
        return userDAO.addUser(user);
    }

    public List<User> getAllUsers() throws SQLException {
        return userDAO.getAllUsers();
    }

    public User getUserById(int userId) throws SQLException {
        return userDAO.getUserById(userId);
    }

    public boolean updateUser(User user) throws SQLException {
        return userDAO.updateUser(user);
    }

    public boolean deleteUser(int userId) throws SQLException {
        return userDAO.deleteUser(userId);
    }

    public boolean changePassword(int userId, String newPassword) throws SQLException {
        String hashedPassword = PasswordUtil.hashPassword(newPassword);
        return userDAO.updateUserPassword(userId, hashedPassword);
    }
}